package com.leha.mp.core.services.imp;

import com.leha.mp.core.dao.MpMenuMapper;
import com.leha.mp.core.entity.mybatis.MpMenu;
import com.leha.mp.core.entity.mybatis.MpMenuExample;
import com.leha.mp.core.services.WxMPServices;
import com.leha.mp.core.services.WxMenuServices;
import me.chanjar.weixin.common.bean.menu.WxMenu;
import me.chanjar.weixin.common.bean.menu.WxMenuButton;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
@Service
public class WxMenuServicesImpl implements WxMenuServices {
    @Autowired
    MpMenuMapper menuMapper;
    @Autowired
    WxMPServices wxMPServices;

    private List<MpMenu> findMenu(Integer pid) {
        MpMenuExample ex = new MpMenuExample();
        ex.createCriteria().andPIdEqualTo(pid);
        ex.setOrderByClause("sort asc");
        return menuMapper.selectByExample(ex);
    }

    @Override
    public boolean updateWxMenu() {
        WxMenu menu = new WxMenu();
        List<MpMenu> vMenus = findMenu(0);
        if(vMenus.size()>0){
            for (MpMenu vMenu:vMenus){
                WxMenuButton rootButton = new WxMenuButton();
                rootButton.setName(vMenu.getName());
                rootButton.setType(vMenu.getType());
                rootButton.setUrl(vMenu.getUrl());
                rootButton.setAppId(vMenu.getAppId());
                rootButton.setPagePath(vMenu.getPagepath());
                List<MpMenu> vMenus1 = findMenu(vMenu.getId());
                if(vMenus1.size()>0){
                    for (MpMenu menu1:vMenus1){
                        WxMenuButton subBtn = new WxMenuButton();
                        subBtn.setType(menu1.getType());
                        subBtn.setName(menu1.getName());
                        subBtn.setUrl(menu1.getUrl());
                        subBtn.setAppId(vMenu.getAppId());
                        subBtn.setPagePath(vMenu.getPagepath());
                        rootButton.getSubButtons().add(subBtn);
                    }
                }
                menu.getButtons().add(rootButton);
            }
        }
        try{
            this.wxMPServices.getWXServies().getMenuService().menuCreate(menu);
        } catch(Exception e) {
            return false;
        }
        return true;
    }
}
